<?php
/**
 * 催缴通知
 * User: wuhao
 * Date: 2017/5/25
 * Time: 9:51
 */
namespace app\backend\controller;
use app\backend\controller\traits\AuthManager;
use app\backend\model\BillManager;
use app\backend\model\Building;
use app\backend\model\IncomeNotice;
use app\backend\model\Lease;
use app\backend\model\Member;
use app\backend\model\MessageTemplate;
use app\backend\model\PayNotice;
use Business\Business;
use think\Controller;

class PayNoticeListController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype    = null;
    private $_pdtype   = null;
    private $_pmid     = null;
    private $_allAuth  = [];
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }

    /**
     * 人工发送催缴短信
     * @date   2017-05-25
     * @author wuhao
     *
     * @param  array   $orderId  账单id数组
     * @param  string  $ordernum 账单号
     * @param  int     $beginCycle  周期开始20170406
     * @param  int     $endCycle  周期结束 20170505
     * @param  int     $sendNow   是否立即发送 0=否
     * @return json
     */
    public function manualSend()
    {
        if (!in_array($this->_pdtype, [1,3,4,5,6])) {
            $this->apiReturn(400, [], '无权操作');
        }

        $orderId    = I('post.order_id');
        $ordernum   = I('post.ordernum', '', 'strval');
        $beginCycle = I('post.begin_cycle', '', 'intval');
        $endCycle   = I('post.end_cycle', '', 'intval');
        $sendNow    = I('post.send_status', 0, 'intval');
        $orderId    = json_decode($orderId, true);
        //$orderId=[3696, 4288, 4289, 4290];$ordernum='149500801179';$beginCycle='20151115';$endCycle='20151214';
        if (!$orderId || !$ordernum || !$beginCycle ||!$endCycle || !is_array($orderId)) {
            $this->apiReturn(400, [], '所传参数有误');
        }
        //获取租赁催缴配置
        $tplModel = new MessageTemplate();
        $tplInfo  = $tplModel->getTemplateByPayOrIncome(1, 1, 1);
        if (!$tplInfo) {
            exit('模板未配置');
        }
        $content = json_decode($tplInfo[0]['content'], true);

        $billModel = new BillManager();
        //获取这个用户应付账单的id
        $idArr = $billModel->getBillDetailByOwner($this->_pmid, $this->_pdtype, $ordernum, $beginCycle, $endCycle, 0, 'id, tenant_id, money, type_money, building_id');
        if (!$idArr) {
            $this->apiReturn(202, [], '找不到对应账单');
        }
        $orderArray = array_column($idArr, 'id');
        $tenantId  = $idArr[0]['tenant_id'];//租户id
        $buildingId = $idArr[0]['building_id'];
        $detail = $moneyDetail = '';
        $totalMoney = 0;
        //判断所传账单id数组是否在该用户的应收id里
        foreach ($orderId as $key => $id) {
            if (!in_array($id, $orderArray)) {
                $this->apiReturn(207, [], '账单id有误');
            }
            foreach ($idArr as $k => $v) {
                if ($v['id'] == $id) {
                    $moneyDetail .= getMoneyType($v['type_money']) . ' ' . ($v['type_money'] ==9 ? yuan($v['money'])*(-1) : yuan($v['money'])) . '元,';
                    $totalMoney += $v['money'];
                    break;
                }
            }
        }

        $moneyDetail = rtrim($moneyDetail, ',');

        //用于拼接短信内容
        $pre = '【租付通】租赁缴费，账单周期';
        $roomPre='房号';
        $total = '总金额为';
        $zd='账单明细';
        $after = '请登录www.louxiaomei.com进行缴费';


        //$memberModel = new Member();
        //获取租户信息
        //$tenantInfo  = $memberModel->getMemberInfoById($tenantId, 'id, mobile');

        //获取这些合同对应的房号
        $leaseModel = new Lease();
        $roomArr = $leaseModel->getLeaseExtByOrderNum($ordernum, 'ordernum, room');
        $rooms = array_column($roomArr, 'room');
        $rooms = implode(',', $rooms);

        $detail = $pre.$beginCycle.'~'.$endCycle.'，'.$roomPre.rtrim($rooms).'，';
        //短信详情保存
        $detail.= $total.yuan($totalMoney).'元，'.$zd.$moneyDetail.'。'.$after;
        //发送短信
        $datas = [];
        $datas[0] = $tplInfo[0]['title'];
        $datas[1] = $datas[2] = $datas[3] = $datas[4] = '';
        $datas[1] = $beginCycle.'~'.$endCycle;
        $datas[2] = $rooms;
        $datas[3] = yuan($totalMoney).'元';
        $datas[4] = $moneyDetail;

        //获取财务联系人电话
        $financeMobile = $leaseModel->getLeaseByOrderNum($ordernum, 'finance_mobile');

        if ($sendNow == 0) {//是否立即发送  否
            $sendData = "【租付通】 ".$datas[0]."账单周期".$datas[1]."，房号".$datas[2]."，总金额为".$datas[3]."，账单明细 ".$datas[4];
            $this->apiReturn(200, ['sms' => $sendData], '');
        } else {//立即发送
            $payNoticeModel = new PayNotice();
            //生成催缴信息
            $pid = $payNoticeModel->addNotice( $financeMobile['finance_mobile'],$tenantId, 1, $ordernum, $beginCycle, $endCycle, $buildingId,  1, 1, 1, 2,
                $totalMoney, $detail, $moneyDetail);
            if (!$pid) {
                $this->apiReturn(205, [], '添加消息队列失败');
            }
            $business = new Business();
            $res = $business->sendPayNotice($financeMobile['finance_mobile'], $datas, $content, 1);
            if ($res['code'] != 200) {//发送成功
                $this->apiReturn(206, [], '短信发送失败');
            }
            //更新发送状态
            $res2 = $payNoticeModel->updateNoticeListStatus($pid, time(), 1);
            if (!$res2) {
                zft_log('message/update', $payNoticeModel->getLastSql());
            }
            $this->apiReturn(200, [], '发送成功');
        }
    }

    /**
     * 获取已发送的短信列表
     * @date   2017-06-14
     * @author wuhao
     *
     * @param  int     $begin  开始时间
     * @param  int     $end    截止时间
     * @param  int     $notifyMethod 通知方式 1=短信
     * @param  int     $eventType  事件类型 1=催缴 2=到账
     * @param  string  $room   房号
     * @param  string  $mobile  手机号
     * @param  int     $page   页数
     * @param  int     $pageSize 每页个数
     * @return json
     */
    public function getSendList()
    {
        if (!in_array($this->_pdtype, [1,3,4,5,6])) {
            $this->apiReturn(400, [], '无权操作');
        }
        $begin        = I('post.begin', '', 'intval');
        $end          = I('post.end', '', 'intval');
        $notifyMethod = I('post.notify_method', 1, 'intval');
        $eventType    = I('post.event_type', '1', 'intval');
        $room         = I('post.room', '', 'strval');
        $mobile       = I('post.mobile', '', 'strval');
        $page         = I('post.page', 1, 'intval');
        $pageSize     = I('post.page_size', '15','intval');
        //$room='1401';
        //$begin=strtotime('-1day');$end=time();$eventType=1;
        if (!$begin || !$end) {//默认查今天的
            $begin = strtotime(date('Ymd'));
            $end   = time();
        } else {
            $end += 86399;
        }
        $buildingModel = new Building();
        $houseList = $this->getHouseInfo($buildingModel, $this->_pmid, $this->_pdtype);
        if (!$houseList) {
            $this->apiReturn(400, [], '暂无数据');
        }

        //是否有room查询条件
        if ($room) {
            $roomInfo = $buildingModel->getHouseList(['room' => $room, 'is_delete'=>0], 'house_number');
            if (!$roomInfo) {
                $this->apiReturn(400, [], '暂无数据');
            }

            $tmp = '';
            foreach ($roomInfo as $r) {
                if (in_array($r['house_number'], $houseList)) {
                    $tmp = $r['house_number'];
                    break;
                }
            }
            if (!$tmp) {//查到的房源不归自己所管
                $this->apiReturn(400, [], '暂无数据');
            }
            //改变查询房源为该room
            $houseList = [$tmp];
        }

        //根据这些房源编号数组查询对应的订单号
        $leaseModel = new Lease();
        $orderNum = $leaseModel->getLeaseExtByHouse($houseList, 'ordernum');
        if (!$orderNum) {
            $this->apiReturn(400, [], '暂无数据');
        }
        $orderNumArr = array_column($orderNum, 'ordernum');

        if ($eventType == 1) {//催缴记录
            //查找发送记录的合同列表
            $payNoticeModel = new PayNotice();
            $res = $payNoticeModel->getReSendList($begin, $end, $orderNumArr, $mobile, $notifyMethod,
                'id, ordernum, begin_cycle, end_cycle, mobile, send_time, notify_method, detail', $page, $pageSize);
        } else {//到账记录
            $incomeModel = new IncomeNotice();
            $res = $incomeModel->getSendList($begin, $end, $orderNumArr, $mobile, $notifyMethod,
                'id, ordernum, begin_cycle, end_cycle,  mobile, send_time, notify_method, detail', $page, $pageSize);
        }
        if (!$res) {
            $this->apiReturn(400, [], '暂无数据');
        }
        $this->apiReturn(200, $res, '');
    }

    /**
     * 获取与自己相关的房源编号数组
     * @date   2017-06-14
     * @author wuhao
     *
     * @param  Building  $buildModel  楼宇模型
     * @param  int     $memberId    用户id
     * @param  int     $dtype      用户类型
     * @return array
     */
    private function getHouseInfo(Building $buildModel, $memberId, $dtype)
    {
        $houseList = [];
        if ($dtype == 1) {//业主查询自己的房源
            $houseNumber = $buildModel->getHouseInfoByMid($memberId, 'house_number');
            if ($houseNumber) {
                $houseList = array_column($houseNumber, 'house_number');
            }
        } elseif ($dtype == 3 || $dtype == 4) {//查询自己发布的楼宇,找出对应的房源
            $buildId = $buildModel->getBuildByMid($memberId, 'id');
            if ($buildId) {
                $buildIdArr = array_column($buildId, 'id');
                $houseNumber = $buildModel->getHouseInfoByBuildingId($buildIdArr, 'house_number');
                $houseList = $houseNumber ? array_column($houseNumber, 'house_number') : [];
            }
        } else {//物业，水电查询对应的房源
            $buildId = $buildModel->getBuildingList(['property_id|hydropower_id' => $memberId, 'is_delete'=>0], 'id');
            if ($buildId) {
                $buildIdArr = array_column($buildId, 'id');
                $houseNumber = $buildModel->getHouseInfoByBuildingId($buildIdArr, 'house_number');
                $houseList = $houseNumber ? array_column($houseNumber, 'house_number') : [];
            }
        }
        return $houseList;
    }

    /**
     * 重发催缴短信
     * @date   2017-06-15
     * @author wuhao
     *
     * @param  array  $idArr  要重发短信对应的id数组
     * @return json
     */
    public function reSend()
    {
        $idArr = I('post.id_arr');
        $idArr = json_decode($idArr, true);

        //$idArr = [152,153,154];
        if (!$idArr || !is_array($idArr)) {
            $this->apiReturn(400, [], '参数有误');
        }
        $payNoticeModel = new PayNotice();
        $list = $payNoticeModel->getListByWhere(['id'=>['in', $idArr], 'send_status'=>1]);
        if (!$list) {
            $this->apiReturn(400, [], '暂无数据');
        }
        $data = [];
        $now =  time();
        foreach ($list as $v) {//去除重复的
            $has = false;
            foreach ($data as $d) {
                if ($v['ordernum']==$d['ordernum'] && $v['begin_cycle']==$d['begin_cycle'] && $v['end_cycle']==$d['end_cycle']) {
                    $has = true;
                    break;
                }
            }
            if ($has === false) {
                $data[] = [
                    'mid'           => $v['mid'],
                    'contract_type' => $v['contract_type'],
                    'ordernum'      => $v['ordernum'],
                    'mobile'        => $v['mobile'],
                    'begin_cycle'   => $v['begin_cycle'],
                    'end_cycle'     => $v['end_cycle'],
                    'message_type'  => $v['message_type'],
                    'event_type'    => $v['event_type'],
                    'notify_method' => $v['notify_method'],
                    'send_type'     => $v['send_type'],
                    'report_time'   => $now,
                    'priority'      => $v['priority'],
                    //'room'          => $rooms,
                    'total_money'   => $v['total_money'],
                    'detail'        => $v['detail'],
                    'money_detail'  => $v['money_detail'],
                    'send_time'     => 0,
                    'send_status'   => 0,
                ];
            }
        }

        $billModel = new BillManager();
        foreach ($data as $key => $value) {
            //判断是否已经交过钱
            $payState = $billModel->payBillStatus($value['ordernum'], $value['begin_cycle'], $value['end_cycle']);
            if (!$payState || $payState['status'] == 1) {//查不到账单或已经是支付状态
                unset($data[$key]);
            }
        }
        if (!$data) {
            $this->apiReturn(400, [], '账单已支付过了或找不到账单数据');
        }

        //插入到短信列表
        $res = $payNoticeModel->addNoticeList($data);
        if (!$res) {
            $this->apiReturn(400, [], '重新发送失败');
        }
        //发送这些短信
        $this->sendPayLeaseNoticeList($payNoticeModel, $now);
    }

    /**
     * 发送租赁催缴消息队列
     * @date   2017-04-25
     * @author wuhao
     *
     * @param PayNotice $payNoticeModel 模型
     * @param int $now report_time 运行时间
     * @return json
     */
    private function sendPayLeaseNoticeList(PayNotice $payNoticeModel, $now)
    {
        $tplModel       = new MessageTemplate();
        $business       = new Business();
        //获取租赁催缴配置
        $tplInfo = $tplModel->getTemplateByPayOrIncome(1, 1, 1);
        if (!$tplInfo) {
            $this->apiReturn(400, [], '模板未配置');
        }
        $content = json_decode($tplInfo[0]['content'], true);
        $leaseModel = new Lease();
        //获取还未发送的用户消息队列
        $tmpList = $payNoticeModel->getListByWhere(['report_time'=>$now, 'send_status'=>0]);
        if ($tmpList) {
            $orderArr = array_column($tmpList, 'ordernum');
            //获取房号信息
            //获取这些合同对应的房源编号
            $roomArr = $leaseModel->getLeaseExtByOrderNum($orderArr, 'ordernum, room');
            $idArr = [];
            foreach ($tmpList as $key => $t) {//循环发送给每个用户
                $room = '';
                foreach ($roomArr as $r) {
                    if ($r['ordernum'] == $t['ordernum']) {
                        $room .= $r['room'];
                    } else {
                        continue;
                    }
                }
                $datas[0] = $tplInfo[0]['title'];
                $datas[1] = $datas[2] = $datas[3] = $datas[4] = '';
                $datas[1] = $t['begin_cycle'].'~'.$t['end_cycle'];
                $datas[2] = rtrim($room, ',');
                $datas[3] = yuan($t['total_money']).'元';
                $datas[4] = $t['money_detail'];

                //dd($datas);
                $res = $business->sendPayNotice($t['mobile'], $datas, $content, 1);
                if ($res['code'] == 200) {//发送成功
                    $idArr[] = $t['id'];
                }
            }

            if ($idArr) {//更新这些发送成功的短信状态
                $updateStatus = $payNoticeModel->updateNoticeListStatus($idArr, time(), 1);
                if (!$updateStatus) {
                    zft_log('payNotice/updateList', $payNoticeModel->getLastSql());
                }
                unset($idArr);
            }
            $this->apiReturn(200, [], '发送成功');
        } else {
            $this->apiReturn(400, [], '暂无数据');
        }
    }
}